package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.entity.SysUserNew;
import com.itheima.ydd.mapper.SysUserNewMapper;
import com.itheima.ydd.service.ISysUserNewService;
import com.itheima.ydd.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Slf4j
@Service
public class SysUserNewServiceImpl extends ServiceImpl<SysUserNewMapper, SysUserNew> implements ISysUserNewService {


    @Autowired
    private ISysUserService sysUserService;



    /**
     * @description: 添加管理员
     * @author: 黄伟兴
     * @date: 2022/9/8 9:45
     * @param: [user]
     * @return: com.itheima.ydd.common.ResultData
     **/
    @Override
    public ResultData add(SysUserNew userNew) {

        SysUser user = new SysUser();

        BeanUtils.copyProperties(userNew, user, "role_id");

        String[] roleId = userNew.getRoleId();


        ArrayList<String> list = new ArrayList();

        for (int i = 0; i < roleId.length; i++) {
            list.add("\"" + roleId[i] + "\"");
        }

        user.setRoleId(list.toString());


        user.setCreateDate(LocalDateTime.now());
        user.setUpdateDate(LocalDateTime.now());
        user.setDefaultData("1");

        //设置密码 //TODO
        String password = user.getPassword();
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(passwordMd5);


        sysUserService.save(user);

        return ResultData.ok("添加成功", null);
    }

    /**
     * @description: 修改管理员冻结状态 //TODO
     * @author: 黄伟兴
     * @date: 2022/9/8 9:43
     * @param: [userNew]
     * @return: com.itheima.ydd.common.ResultData
     **/
    @Override
    public ResultData updateSysUser(SysUserNew userNew) {
        //数据拷贝
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userNew, user, "role_id");

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getStatus, userNew.getStatus());

        //修改状态
        user.setStatus(userNew.getStatus());
        user.setUpdateDate(LocalDateTime.now());
        sysUserService.updateById(user);
        return ResultData.ok("修改成功！");
    }
}
